
<template>
  <div id="editor—wrapper" style="border: 1px solid #ccc">
    <div id="toolbar-container" style="border-bottom: 1px solid #ccc"><!-- 工具栏 --></div>
    <div id="editor-container" style="height: 300px; overflow-y: hidden;"><!-- 编辑器 --></div>
  </div>

  <el-dialog
    v-model="visible"
    title="Tips"
    width="30%"
  >
    <span>This is a message</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">Cancel</el-button>
        <el-button type="primary" @click="handleConfirm">
          确认插入变量
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { IDomEditor, createEditor, createToolbar, Boot, IEditorConfig } from '@wangeditor/editor'
import { onBeforeUnmount, ref, shallowRef, watch, onMounted } from 'vue'
import { variableConf } from './plugins/variableButton/baseModalMenu'
import module from './plugins/module'

Boot.registerMenu(variableConf)
Boot.registerModule(module)

let editor:IDomEditor
const visible = ref(false)

const toolbarConfig = {
  excludeKeys: [
    'group-image', 'group-more-style', 'group-video', 'emotion', 'insertTable', 'todo', 'codeBlock', 'blockquote'
  ],
  insertKeys: {
    index: 31,
    keys: ['variable']
  },
  mode: 'default'
}
const editorConfig = {
  placeholder: '请输入合同正文...'
}

onMounted(()=>{
  editor = createEditor({
    selector: '#editor-container',
    config: editorConfig
  })

  // 自定义函数，用来展示插入变量弹框
  editor['showVariable'] = () => {
    visible.value = true
  }

  createToolbar({
    editor: editor,
    selector: '#toolbar-container',
    config: toolbarConfig
  })
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  window.commonEditor = editor
})

const handleConfirm = () => {
  visible.value = false
  insertVar()
}

const insertVar = () => {
  const variableElem = {
    type: 'mention',
    varId: 'item.id',
    varName: "name",
    isNotNull: 0,
    value: `{{*杰克}}`,
    children: [{ text: '' }]
  }
  if (editor == null) return
  editor.restoreSelection()
  editor.insertNode(variableElem)
  // 光标移动一位
  editor.move(1)
}
</script>

<style scoped>
</style>
